import axios from 'axios';
import qs from 'qs';
import {API_PATH} from '@/api/index.js';
import {getLocalStorage} from '@/util/local-storge.js';
import Vue from 'vue';
import Router from 'vue-router';
import router from '@/vue/router/index.js';
const instance = axios.create({
	timeout: 5000,
	// baseURL: process.env.NODE_ENV === 'development' ? '/api' : '',
	// headers: header,
	baseURL: API_PATH
});

instance.interceptors.request.use(
	config => {
		if (config.method === 'post' || config.method === 'put') {
			console.log(config.data);
			config.data = JSON.stringify(config.data);
		}
		let token = getLocalStorage('user_token').user_token ? getLocalStorage('user_token').user_token : "";
		let header = "";
		if (token) {
			header = {
				'Content-Type': 'application/json;charset=utf-8',
				'auth-token': token
			}

		} else {
			header = {
				'Content-Type': 'application/json;charset=utf-8',
			}
		}
		config.headers = header;
		/*
		if (!config.headers.Authorization) {
		  config.headers.Authorization = `Bearer ${window.localStorage.getItem(
		    'Authorization'
		  ) || ''}`;
		}
		*/
		return config;
	},
	err => Promise.reject(err)
);

// axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
// axios.defaults.timeout = 50000;
instance.interceptors.response.use(
	res => {
		if (res.data.status == '-1001') {
			  router.push({name: 'login'})
		}

		/*
		if (!res.data.success) {
		  switch (res.data.code) {
		    case 422: {
		      const flag = Array.isArray(res.data.data) && res.data.data.length;
		      Dialog.alert({
		        message: flag ? res.data.data[0].message : res.data.message
		      });
		      break;
		    }
		    case 401:
		      break;
		    case 404:
		      break;
		    default:
		      break;
		  }
		  return Promise.reject(res);
		}
		*/
		return res;
	},
	error => {
		/*
		Dialog.alert({
		  title: '警告',
		  message: error.message
		});
		*/
		return Promise.reject(error);
	}
);

const post = (url, data, config = {}) => instance.post(API_PATH + url, data, config);
const put = (url, data, config = {}) => instance.put(API_PATH + url, data, config);

const get = (url, params, config = {}) =>
	instance.get(API_PATH + url, {
		params,
		...config
	});

const deleteMethod = (url, config = {}) =>
	instance({
		url: API_PATH + url,
		method: 'delete',
		...config
	});

export default {
	install(Vue) {
		Vue.prototype.$reqGet = get;
		Vue.prototype.$reqPost = post;
		Vue.prototype.$reqPut = put;
		Vue.prototype.$reqDel = deleteMethod;
	}
};
